package com.happystreet.loader
{
	import flash.events.Event;

	/**
	 *加载队列 
	 * @author Liseen
	 * 
	 */	
	public class LoadingQueue
	{
		public var completeCounter:int;
		private var _queue:Vector.<LoadingQueueItem>;
		private var _running:Boolean;
		private var _parallelLoading:Boolean;
		private var _parallelLoadingQueue:Vector.<LoadingQueueItem>;
		private var _currentItem:LoadingQueueItem;
		private var _callBack:Function;
		public function LoadingQueue()
		{
			_queue = new Vector.<LoadingQueueItem>;
			_running = false;
			_parallelLoading = false;
			_parallelLoadingQueue = new Vector.<LoadingQueueItem>;
			completeCounter = 0;
			_callBack=null;
			
			
		}
		/**
		 *添加到队列对象到队列中 
		 * @param item	LoadingQueueItem	
		 * 
		 */		
		public function addItem(item:LoadingQueueItem):void{
			_queue.push(item);
			if(_parallelLoading){
				_parallelLoadingQueue.push(item);
				completeCounter++;
			}
			
			if(!this._running||this._parallelLoading){
				this._running=true;
				runQueue();
			}
		}
		
		/**
		 *运行队列 
		 * 
		 */		
		public function runQueue():void{
			this._currentItem = this._queue.shift();
			if(this._currentItem!=null){
				this._currentItem.registerCompleteHandlerForQueue(this.onItemComplete);
				this._currentItem.startLoad(this._parallelLoading);
			}else{
				if(!this._parallelLoading){
					if(this._queue.length==0){
						this._running=false;
						this.notifyAllItemsComplete();
					}else{
						this.runQueue();
					}
				}
			}
		}
		
		/**
		 *注册队列加载完成回调处理 
		 * @param value
		 * 
		 */		
		public function registerCompleteHandler(value:Function):void{
			_callBack = value;
		}
		
		/**
		 *处理队列加载时需要设置此参数为true 
		 * @param value
		 * 
		 */		
		public function set parallelLoading(value:Boolean):void{
			this._parallelLoading = value;
		}
		
		/**
		 *通知队列加载完成 
		 * 
		 */		
		private function notifyAllItemsComplete():void{
			if(this._callBack!=null&&(this._callBack is Function)){
				_callBack();
			}
		}
		/**
		 *加载单元完成 
		 * @param event
		 * 
		 */		
		private function onItemComplete(event:Event):void{
			if(this._parallelLoading){
				this.completeCounter--;
			}else{
				this.runQueue();
			}
			
			if(this.completeCounter==0){
				this.notifyAllItemsComplete();
			}
		}
	}
}